package logic

import (
	"context"
	"encoding/json"
	"sort"
	"strings"

	"lottery-zero/external/utils"
	"lottery-zero/internal/model"
	"lottery-zero/internal/svc"
	"lottery-zero/internal/types"

	"github.com/tal-tech/go-zero/core/logx"
	"gorm.io/gorm/clause"
)

type LottobetLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewLottobetLogic(ctx context.Context, svcCtx *svc.ServiceContext) LottobetLogic {
	return LottobetLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *LottobetLogic) Lottobet(req types.LottoBetReq, userId string) (*types.CodeReply, error) {
	// todo: add your logic here and delete this line
	userInt, _ := json.Number(userId).Int64()
	for _, bet := range req.Bets {
		sort.SliceStable(bet.Front, func(i, j int) bool {
			return bet.Front[i] < bet.Front[j]
		})
		sort.SliceStable(bet.Back, func(i, j int) bool {
			return bet.Back[i] < bet.Back[j]
		})
		front := strings.Join(utils.BollIntToStrSlice(bet.Front), " ")
		back := strings.Join(utils.BollIntToStrSlice(bet.Back), " ")
		switch req.DrawNum {
		case "forever":
			udb := model.UserLotteryForever{UserID: uint(userInt), Comment: req.Comment, Front: front, Back: back, Last: 99999}
			l.svcCtx.PGDB.Clauses(clause.OnConflict{DoNothing: true}).Create(&udb)
		case "forever-3":
			udb := model.UserLotteryForever{UserID: uint(userInt), Comment: req.Comment, Front: front, Back: back, Last: 3}
			l.svcCtx.PGDB.Clauses(clause.OnConflict{DoNothing: true}).Create(&udb)
		case "forever-12":
			udb := model.UserLotteryForever{UserID: uint(userInt), Comment: req.Comment, Front: front, Back: back, Last: 12}
			l.svcCtx.PGDB.Clauses(clause.OnConflict{DoNothing: true}).Create(&udb)
		case "forever-244":
			udb := model.UserLotteryForever{UserID: uint(userInt), Comment: req.Comment, Front: front, Back: back, Last: 244}
			l.svcCtx.PGDB.Clauses(clause.OnConflict{DoNothing: true}).Create(&udb)
		default:
			udb := model.UserLotteryTicket{UserID: uint(userInt), IsOpen: false, Comment: req.Comment, DrawNum: req.DrawNum, Front: front, Back: back}
			l.svcCtx.PGDB.Clauses(clause.OnConflict{DoNothing: true}).Create(&udb)
		}

	}

	return &types.CodeReply{Code: 200, Msg: "success"}, nil
}
